<?php

namespace app\api\controller;

use app\common\controller\Api;
use EasyWeChat\Factory;

/**
 * 微信小程序登录接口
 */
class Login extends Api
{
    protected $noNeedLogin = ['login'];
    protected $noNeedRight = ['login'];

    /**
     * 授权接口
     *
     * @ApiTitle    (授权接口)
     * @ApiSummary  (授权接口)
     * @ApiMethod   (POST)
     * @ApiRoute    (/api/login/login)
     * @ApiParams   (name="code", type="varchar", required=true, description="用户code")
     * @ApiParams   (name="nickname", type="varchar", required=true, description="昵称")
     * @ApiParams   (name="avatar", type="varchar", required=true, description="头像")
     * @ApiReturnParams   (name="code", type="integer", required=true, sample="0")
     * @ApiReturnParams   (name="msg", type="string", required=true, sample="返回成功")
     * @ApiReturnParams   (name="data", type="object", sample="", description="扩展数据返回")
     * @ApiReturnParams   (name="id", type="integer",, description="用户id")
     * @ApiReturnParams   (name="token", type="varchar",, description="token")
     * @ApiReturn   ({
    'code':'1',
    'msg':'返回成功'
    })
     */
    public function login() {
        /*$param = $this->request->param();
        $code = $param['code'];
        $nickname = $param['nickname'];
        $avatar = $param['avatar'];
        //获取微信配置信息
        $config = config('wechat_config');
        $app  = Factory::miniProgram($config);
        $info = $app->auth->session($code);
        if(!isset($info['openid'])){
            $this->error('code有误');
        }
        $openid = $info['openid'];*/
        $openid = "C9vlYPy4F8FgMZR6NDqPN1jzB1AL7Vt5";
        $nickname = "老汉";
        $avatar = "111";
        //实例化
        $authapplet = new Authapplet;
        //判断该openid是否在系统中存在
        $hasUser = $authapplet->hasUser($openid);
        //如果存在
        if($hasUser){
            //更新token 和 昵称 和头像
            $updaToken = $authapplet->updaToken($hasUser['id'],$nickname,$avatar);
            //返回信息
            if($updaToken['code'] == 1){
                $this->success($updaToken['msg'],$updaToken['data']);
            }else{
                $this->error($updaToken['msg']);
            }
            //如果不存在
        }else{
            //重新注册
            $register = $authapplet->register($openid,$nickname,$avatar,0);
            //返回信息
            if($register){
                $this->success('注册成功',$register);
            }else{
                $this->error($register);
            }
        }
    }
}
